//
//  YJMUserAccountViewModel.swift
//  Weibo
//
//  Created by 杨军民 on 16/7/21.
//  Copyright © 2016年 杨军民. All rights reserved.
//

import UIKit

/*
1、沙盒保存分为两步
a、保存数据到沙盒中
b、保存的路经

2、读取数据也是两步
a、读书数据
b、加载沙盒数据

3、用户是否登录
a、根据userAccount是否为空来判断

4、读取沙盒数据
a、user头像和user名称(使用过多的if let会造成嵌套太多：使用守卫：和if let 相反，他是当数据没有值的时候才会进去)

*/

class YJMUserAccountViewModel: NSObject {

    //单例
    static let sharedUserAccountViewModel : YJMUserAccountViewModel = YJMUserAccountViewModel()
    
    //
    var userAccount : YJMUserAccount?
    
    //用于获取数据
    var avatar_token :String?
    
    //用户是否登录
    var userLogin : Bool {
        get{
            //要是有账号就是登录
            return userAccount != nil
        }
    }
    
    //账号保存的路径
    let userAccountFile = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("/userAccount.plist")
    
    //读取沙盒的数据
    override init() {
        super.init()
        userAccount = loadUserAccount()
    }
    
    //获取user头像和名称
    func loadUserInfo(completion: (error:NSError?) ->() ) {
        //守卫
        guard let access_token = userAccount?.access_token else{
            print("avatar_token没有值的时候就不会发送网络请求")
            return
        }
        
        guard let uid = userAccount?.uid else{
            print("uid没有值的时候就不会发送网络请求")
            return
        }
        
        //URLString
        let URLStirng = "2/users/show.json"
        //参数
        let parameters = [
            "access_token" : access_token,
            "uid" : uid
        ]
        
        //发送请求
       YJMNetWorkTools.sharedNetworkTool1.GET(URLStirng, parameters: parameters, progress: nil, success: { (_, responseObjce) -> Void in
        //获取用户的头像和名称地址
//        let dic = responseObjce as? [String:AnyObject]
        let dic = responseObjce as? [String: AnyObject]
        let screen_name = dic?["screen_name"] as? String
        let avatar_large = dic?["avatar_large"] as? String
        
        //给userAccount赋值
        self.userAccount?.screen_name = screen_name
        self.userAccount?.avatar_large = avatar_large
        
        //将模型重新保存到沙盒中
        self.saveUserAccount(self.userAccount!)
        
        //告诉他人获取到了数据
        completion(error: nil)
        
        }){ (_, error) -> Void in
            print("请求用户数据失败: \(error)")
            //获取数据失败
            completion(error: error)
        }
        
    }
    
    //服务器请求AccessToken
     func loadAccessToken(code : String,completion: (error: NSError?) -> Void) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        print(code)
        // 参数
        let parameters = [
            "client_id" : client_id,
            "client_secret" : client_secret,
            "grant_type" : "authorization_code",
            "code": code,
            "redirect_uri" : redirect_uri
        ]
        
        //使用AFN发送的POST请求
        //        YJMNetWorkTools.sharedNetworkTool1.POST(urlString,parameters:parameters,Process:nil,success:{(_,resopnseOjbect)-> Void in
        
        YJMNetWorkTools.sharedNetworkTool1.POST(urlString, parameters: parameters, progress: nil, success: { (_, responseObject) -> Void in
            
            //字典转模型
            let dic = responseObject as! [String : AnyObject]
            let userAccount = YJMUserAccount(dic: dic)
            
            print("userAccount = \(userAccount)")
            self.userAccount = userAccount;
            //保存数据到沙盒中
//            NSKeyedArchiver.archiveRootObject(self.userAccount!, toFile: self.userAccountFile)
            self.saveUserAccount(self.userAccount!)
            
            completion(error: nil)
            
            }) { (_, error) -> Void in
                
            print("error\(error)")
            completion(error: error)
        }
    }
    
    //保存模型数据到沙盒中
    private func saveUserAccount(userAccount:YJMUserAccount){
     NSKeyedArchiver.archiveRootObject(self.userAccount!, toFile: self.userAccountFile)
    }
    
    //加载沙盒数据
    private func loadUserAccount()->YJMUserAccount? {
        
     let account = NSKeyedUnarchiver.unarchiveObjectWithFile(userAccountFile) as? YJMUserAccount
        
        //判断是否有过期的账号
        if account != nil && account?.expeires?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
            print("没有过期的账号")
            return account
        }
        return nil
    }

}
